<template>
  <my-window :title="title" :modal="modal" :wrapper-closable="true" :modal-append-to-body="modalAppendToBody"
    :visible.sync="visible" destroy-on-close size="100%" width="95%"
    drawer-body-style="padding:0px;height: calc(100% - 61px);" :before-close="onCancel">
    <my-container v-loading="pageLoading" style="display: flex; flex-direction: column;">
      <div style="flex: none ;">
        <el-form ref="header" :model="form.header" :rules="modelRules" label-width="80px" :inline="false">
          <el-row>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="发料单号" prop="orderNo">
                <el-input v-model="form.header.orderNo" readonly autocomplete="off" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="发料日期" prop="orderDate">
                <el-date-picker v-model="form.header.orderDate" type="date" format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="工单号" prop="workOrderNo">
                <el-input v-model="form.header.workOrderNo" placeholder="请输入或选择工单"
                  @click.native="onOpenWorkOrder('header')" class="input-with-select">
                  <el-button slot="append" icon="el-icon-more" @click="onOpenWorkOrder('header')" />
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <!--记录操作-->
        <el-form class="ad-form-query" :inline="true" @submit.native.prevent>
          <el-form-item>
            <el-button type="primary" plain @click="onAddRow">新增</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-scrollbar>
        <div style="display: flex; flex: auto;">
          <el-table ref="rowTable" v-loading="listLoading" :data="form.rows" highlight-current-row height="460"
            :border="true" style="width: 100%;">
            <el-table-column prop="row" align="center" label="行号" width="50">
              <template slot-scope="scop">
                {{scop.$index+1}}
              </template>
            </el-table-column>
            <el-table-column prop="materialCode" align="center" label="物料编码" width="160" />
            <el-table-column prop="materialName" align="center" label="物料名称" width="240" />
            <el-table-column prop="pcs" align="center" label="单箱数量" width="150" />
            <el-table-column prop="qty" align="center" label="数量" width="150" />
            <el-table-column prop="count" align="center" label="件数" width="100" />
            <el-table-column prop="storageLocationCode" align="center" label="库位" min-width="160" />
            <el-table-column prop="description" align="center" label="备注" min-width="200" />
            <el-table-column fixed="right" align="center" label="操作" width="160">
              <template #default="{ $index, row }">
                <el-button plain @click="onEditRow($index, row)">编辑
                </el-button>
                <my-confirm-button v-if="mode === 'add'" type="delete" :loading="row._loading" :validate-data="row"
                  @click="onDeleteRow($index, row)" />
                <el-button v-else-if="mode ==='edit' && row.enabled" type="danger" :loading="row._loading"
                  :validate-data="row" @click="onCancelRow($index, row)" plain>取消</el-button>
                <el-button v-else type="danger" :loading="row._loading" :validate-data="row"
                  @click="onResumeRow($index, row)" plain>恢复</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-scrollbar>

      <!--新增行窗口-->
      <my-window title="新增" :visible.sync="addFormVisible" @close="closeAddForm">
        <el-form ref="addForm" :model="addForm" label-width="100px" :rules="formRules">
          <el-form-item label="物料编码" prop="materialCode">
            <el-input v-model="addForm.materialCode" placeholder="请输入物料" @click.native="onOpenMaterial('addForm')">
              <el-button slot="append" icon="el-icon-more" @click="onOpenMaterial('addForm')" />
            </el-input>
          </el-form-item>
          <el-form-item label="物料名称" prop="materialName">
            <el-input v-model="addForm.materialName" disabled auto-complete="off" />
          </el-form-item>
          <el-form-item label="单箱数量" prop="pcs">
            <el-input v-model.number="addForm.pcs" auto-complete="off" />
          </el-form-item>
          <el-form-item label="数量" prop="qty">
            <el-input v-model.number="addForm.qty" auto-complete="off" />
          </el-form-item>
          <el-form-item label="件数" prop="count">
            <el-input v-model.number="addForm.count" auto-complete="off" />
          </el-form-item>
          <el-form-item label="库位" prop="storageLocationCode">
            <el-input v-model="addForm.storageLocationCode" placeholder="请输入库位"
              @click.native="onOpenStorageLocation('addForm')">
              <el-button slot="append" icon="el-icon-more" @click="onOpenStorageLocation('addForm')" />
            </el-input>
          </el-form-item>
          <el-form-item label="说明" prop="description">
            <el-input v-model="addForm.description" type="textarea" rows="4" auto-complete="off" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click.native="addFormVisible = false">取消</el-button>
            <my-confirm-button type="submit" :loading="addLoading" :validate="addFormValidate" @click="onAddSubmit" />
          </div>
        </template>

        <my-select-storage-location :visible.sync="storageLocationVisible" :form="storageLocationForm"
          @click="onSelectStorageLocation" />
        <my-select-material :visible.sync="materialVisible" :form="materialForm" @click="onSelectMaterial" />
      </my-window>

      <!--编辑窗口-->
      <my-window title="编辑" :visible.sync="editFormVisible" @close="closeEditForm">
        <el-form ref="editForm" :model="editForm" label-width="100px" :rules="formRules">
          <el-form-item label="物料编码" prop="materialCode">
            <el-input v-model="editForm.materialCode" placeholder="请输入物料" @click.native="onOpenMaterial('editForm')">
              <el-button slot="append" icon="el-icon-more" @click="onOpenMaterial('editForm')" />
            </el-input>
          </el-form-item>
          <el-form-item label="物料名称" prop="materialName">
            <el-input v-model="editForm.materialName" disabled auto-complete="off" />
          </el-form-item>
          <el-form-item label="单箱数量" prop="pcs">
            <el-input v-model.number="editForm.pcs" auto-complete="off" />
          </el-form-item>
          <el-form-item label="数量" prop="qty">
            <el-input v-model.number="editForm.qty" auto-complete="off" />
          </el-form-item>
          <el-form-item label="件数" prop="count">
            <el-input v-model.number="editForm.count" auto-complete="off" />
          </el-form-item>
          <el-form-item label="库位" prop="storageLocationCode">
            <el-input v-model="editForm.storageLocationCode" placeholder="请输入库位"
              @click.native="onOpenStorageLocation('editForm')">
              <el-button slot="append" icon="el-icon-more" @click="onOpenStorageLocation('editForm')" />
            </el-input>
          </el-form-item>
          <el-form-item label="说明" prop="description">
            <el-input v-model="editForm.description" type="textarea" rows="4" auto-complete="off" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click.native="editFormVisible = false">取消</el-button>
            <my-confirm-button type="submit" :loading="editLoading" :validate="editFormValidate"
              @click="onEditSubmit" />
          </div>
        </template>

        <my-select-storage-location :visible.sync="storageLocationVisible" :form="storageLocationForm"
          @click="onSelectStorageLocation" />
        <my-select-material :visible.sync="materialVisible" :form="materialForm" @click="onSelectMaterial" />
      </my-window>

      <my-select-work-order :visible.sync="workOrderVisible" :form="workOrderForm" @click="onSelectWorkOrder" />
    </my-container>
    <template #footer>
      <el-button @click.native="onCancel">取消</el-button>
      <el-button type="primary" @click="onSure">确定</el-button>
    </template>
  </my-window>
</template>

<script>
  import {
    formatTime
  } from '@/utils'
  import {
    get as getWorkOrder
  } from '@/api/pm/work-order'
  import {
    getBom
  } from '@/api/base-data/bom'
  import {
    get,
    getList,
    add,
    update,
    softDelete,
    getListPage,
    batchSoftDelete
  } from '@/api/wm/request-order'
  import MyContainer from '@/components/my-container'
  import MyConfirmButton from '@/components/my-confirm-button'
  import MySearch from '@/components/my-search'
  import MySearchWindow from '@/components/my-search-window'
  import MyWindow from '@/components/my-window'
  import MySelectWorkOrder from '@/components/my-select-window/work-order'
  import MySelectMaterial from '@/components/my-select-window/material'
  import MySelectStorageLocation from '@/components/my-select-window/storage-location'

  export default {
    name: 'RequestOrder',
    _sync: {
      disabled: false,
      desc: '',
      cache: true
    },
    components: {
      MyContainer,
      MyConfirmButton,
      MySearch,
      MySearchWindow,
      MyWindow,
      MySelectWorkOrder,
      MySelectMaterial,
      MySelectStorageLocation
    },
    props: {
      title: {
        type: String,
        default: '领料单'
      },
      visible: {
        type: Boolean,
        default: false
      },
      form: {
        type: Object,
        default: ''
      },
      modal: {
        type: Boolean,
        default: false
      },
      modalAppendToBody: {
        type: Boolean,
        default: false
      }
    },
    data() {
      const validatePhone = (rule, value, callback) => {
        if (!value) {
          callback()
        }
        const reg = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
        if (!reg.test(value)) {
          callback(new Error('请输入正确的手机号码!'))
        } else {
          callback()
        }
      }

      return {
        //窗体是否显示
        workOrderForm: null,
        workOrderVisible: false,

        materialForm: null,
        materialVisible: false,

        storageLocationForm: null,
        storageLocationVisible: false,

        mode: 'add',
        listLoading: false,

        pageLoading: false,
        formRules: {
          materialCode: [{
            required: true,
            message: '请输入或选择物料',
          }],
          qty: [{
            required: true,
            message: '请输入数量',
          }],
        },

        // 新增界面相关
        addFormVisible: false, // 新增界面是否显示
        addLoading: false,
        addForm: {
          materialCode: '',
          materialName: '',
          pcs: 0,
          qty: 1,
          count: 0,
          storageLocationCode: '',
          index: 0,
        },

        // 编辑界面相关
        editFormVisible: false, // 编辑界面是否显示
        editLoading: false,
        editForm: {
          materialCode: '',
          materialName: '',
          pcs: 0,
          qty: 1,
          count: 0,
          storageLocationCode: '',
          index: 0,
        },

        modelRules: {
          workOrderNo: [{
            required: true,
            message: '请输入或选择工单',
          }],
          orderDate: [{
            required: true,
            message: '请选择日期',
          }]
        },
      }
    },
    methods: {
      // 取消
      onCancel() {
        this.$emit('update:visible', false)
        this.$emit('cancel')
      },
      // 确定
      onSure() {
        if (this.form.rows.length == 0) {
          this.$message({
            message: '请增加行数据',
            type: 'error'
          })
          return
        }
        for (let i = 0; i < this.form.rows.length; i++) {
          this.form.rows[i].row = i + 1
        }
        this.$emit('click')
      },
      // 新增行事件相关
      async onAddRow() {
        this.addFormVisible = true
        this.editForm.index = this.form.rows.length
      },
      closeAddForm() {
        this.$refs.addForm.resetFields()
      },
      addFormValidate: function() {
        let isValid = false
        this.$refs.addForm.validate(valid => {
          isValid = valid
        })
        return isValid
      },
      async onAddSubmit() {
        this.addLoading = true
        const para = _.cloneDeep(this.addForm)
        para.isQualified = true
        para.enabled = true
        this.form.rows.push(para)
        this.addLoading = false
        this.$refs['addForm'].resetFields()
        this.addFormVisible = false
      },
      // 编辑行事件相关
      async onEditRow(index, row) {
        this.editForm = row
        this.editForm.index = index
        this.editFormVisible = true
      },
      closeEditForm() {
        this.$refs.editForm.resetFields()
      },
      // 编辑验证
      editFormValidate() {
        let isValid = false
        this.$refs.editForm.validate(valid => {
          isValid = valid
        })
        return isValid
      },
      // 编辑
      async onEditSubmit() {
        this.editLoading = true
        const para = _.cloneDeep(this.editForm)
        this.form.rows[para.index] = para
        this.editLoading = false
        this.$refs['editForm'].resetFields()
        this.editFormVisible = false
        this.$refs.rowTable.setCurrentRow(null);
      },
      // 删除行
      async onDeleteRow(index, row) {
        this.addLoading = true
        this.form.rows.splice(index, 1)
        this.addLoading = false
      },

      // 取消行
      async onCancelRow(index, row) {
        this.addLoading = true
        this.form.rows[index].enabled = false
        this.addLoading = false
      },
      // 恢复行
      async onResumeRow(index, row) {
        this.addLoading = true
        this.form.rows[index].enabled = true
        this.addLoading = false
      },
      // 弹框
      onOpenWorkOrder(form) {
        this.workOrderVisible = true
        this.workOrderForm = form
      },
      onSelectWorkOrder(form, selectData) {
        if (selectData) {
          this[form].workOrderId = selectData.id
          this.setWorkOrderInfo()
        }
        this.workOrderVisible = false
      },
      onOpenMaterial(form) {
        this.materialVisible = true
        this.materialForm = form
      },
      onSelectMaterial(form, selectData) {
        if (selectData) {
          this[form].materialId = selectData.id
          this[form].materialCode = selectData.code
          this[form].materialName = selectData.name
          this[form].specification = selectData.specification
        }
        this.materialVisible = false
      },
      onOpenStorageLocation(form) {
        this.storageLocationVisible = true
        this.storageLocationForm = form
      },
      onSelectStorageLocation(form, selectData) {
        if (selectData) {
          this[form].storageLocationCode = selectData.code
          this[form].storageLocationId = selectData.id
        }
        this.storageLocationVisible = false
      },
      async setWorkOrderInfo() {
        //获取工单信息
        const res = await getWorkOrder({
          id: this.header.workOrderId
        })
        this.header.workOrderNo = res.data.orderNo
        //获取物料bom信息
        var productId = res.data.productId
        const res2 = await getBom({
          productId: productId
        })
        this.form.rows = []
        res2.data.forEach(item => {
          this.form.rows.push({
            materialId: item.subId,
            materialCode: item.subCode,
            materialName: item.subName,
            specification: item.subSpecification,
            isQualified: true,
            qty: item.qty * res.data.planQty
          })
        })
      },
    }
  }
</script>

<style lang="scss" scoped>
  .my-search ::v-deep .el-input-group__prepend {
    background-color: #fff;
  }

  .el-date-editor.el-input,
  .el-date-editor.el-input__inner {
    width: 100%;
    margin-left: 0px;
  }
</style>
